package com.threeox.commonlibrary.util.engine;

import android.content.Context;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.entity.engine.verify.VerifyMsg;
import com.threeox.commonlibrary.util.JSONUtils;
import com.threeox.commonlibrary.util.ViewUtils;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.RegexUtils;
import com.threeox.utillibrary.util.ToastUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @ClassName: VerifyFactory
 *
 * @Description: TODO(校验数据的工厂类)
 *
 * @author 赵屈犇
 *
 * @date 创建时间: 2017/7/5 17:22
 *
 * @version 1.0
 *
 */
public class VerifyFactory {

    private Context mContext;

    private VerifyFactory(Context context) {
        this.mContext = context;
    }

    public static VerifyFactory newInstance(Context context){
        return new VerifyFactory(context);
    }

    /**
     * 校验参数
     *
     * @param verifyMsgs
     * @param params
     * @return  true 就是通过检验   false就是不通过校验
     */
    public boolean verify(List<VerifyMsg> verifyMsgs, JSONObject params) {
        if (EmptyUtils.isNotEmpty(verifyMsgs)) {
            for (VerifyMsg verifyMessage: verifyMsgs) {
                String verifyCode = verifyMessage.getVerifyCode();
                Object value = JSONUtils.getJSONValue(params, verifyCode);
                if (verifyMessage.isVerifyEmpty()) {// 检验参数是否为空
                    if (EmptyUtils.isEmpty(value)) {
                        ToastUtils.showShortToast(mContext, getEmptyHint(verifyMessage));
                        return false;
                    }
                }
                if (EmptyUtils.isNotEmpty(verifyMessage.getRegularExp())) {// 校验正则表达式
                    Pattern p = Pattern.compile(verifyMessage.getRegularExp());
                    Matcher m = p.matcher(String.valueOf(value));
                    if (!m.find()) {
                        ToastUtils.showShortToast(mContext, getRegularHint(verifyMessage));
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 得到参数为空时的提示文字
     *
     * @return
     */
    private String getEmptyHint(VerifyMsg verifyMsg) {
        if (EmptyUtils.isNotEmpty(verifyMsg.getEmptyHint())) {
            return verifyMsg.getEmptyHint();
        } else {
            return EmptyUtils.isNotEmpty(verifyMsg.getVerifyName()) ? verifyMsg.getVerifyName() : verifyMsg.getVerifyCode() + "不能为空!";
        }
    }

    /**
     * 得到正则表达式不匹配时的提示文字
     *
     * @return
     */
    private String getRegularHint(VerifyMsg verifyMsg) {
        if (EmptyUtils.isNotEmpty(verifyMsg.getRegularExpHint())) {
            return verifyMsg.getRegularExpHint();
        }
        return getEmptyHint(verifyMsg);
    }

}
